﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
// Mp3Cleaner, Copyright Mirosław M. Mączka.  All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
//
namespace Mp3Cleaner
{
    public class WinylTrackNumbers
    {
        // A1, A2, A3, B1, B2
        // A-1, A-2
        public static bool CnvIfAny(string[] namesOrg, bool [] isChangedOrg)
        {
            //
            // backup
            string[] names = new string[namesOrg.Length];
            Array.Copy(namesOrg, names, namesOrg.Length);
            //
            //
            bool[] isChanged = new bool[isChangedOrg.Length];
            Array.Copy(isChangedOrg, isChanged, isChangedOrg.Length);
            //
            //
            try
            {
                HashSet<string> h = new HashSet<string>();
                foreach (string s in names)
                {
                    string ss = s.Trim();
                    if (ss.Length < 3) return false;
                    string vnum = ss.Substring(0, 2).ToUpper();
                    if (!isVinylNumber(vnum)) return false;
                    h.Add(vnum);
                }
                //
                if (h.Count != names.Length)
                {
                    return false;
                }
                //
                List<string> l = h.ToList();
                l.Sort();
                //
                for (int k = 0; k < names.Length; k++)
                //foreach (string tn in names)
                {
                    string vn = names[k].Trim().Substring(0, 2);
                    int n = l.FindIndex(
                        delegate(string s)
                        {
                            return s.EQ(vn);
                        }
                    );
                    if (n != -1)
                    {
                        names[k] = replaceVinylNumber(names[k], n + 1);
                        isChanged[k] = true;
                    }
                }
            }
            catch (Exception e)
            {
                //
                return false;
            }
            //
            Array.Copy(names, namesOrg, namesOrg.Length);
            Array.Copy(isChanged, isChangedOrg, isChangedOrg.Length);
            //
            return true;
        }
        //
        //
        private static bool isVinylNumber(string s)
        {
            return (s.StartsWith("A",StringComparison.InvariantCultureIgnoreCase) || s.StartsWith("B",StringComparison.InvariantCultureIgnoreCase)) && Char.IsNumber(s, s.Length-1);
        }
        //
        private static string replaceVinylNumber(string s, int n)
        {
            return Utils.Number2Track(n) + " " + s.Trim().Substring(2);
        }
        //
    }//class
}//namespace
